package com.gxc.graph;

import java.util.*;

/**
 * 拓扑算法--用于依赖的先后排序
 */
public class Topology {

    public static void main(String[] args) {
        Graph graph = BreadthFirst.createGraph();

        List<Node> list = topology(graph);
    }

    private static List<Node> topology(Graph graph) {
        //当前node的入度
        Map<Node, Integer> inMap = new HashMap<>();
        //入库为0的放入队列
        Queue<Node> zeroInQueue = new LinkedList<>();

        for (Node node : graph.nodes.values()) {
            inMap.put(node, node.in);
            if (node.in == 0) {
                zeroInQueue.add(node);
            }
        }

        List<Node> result = new ArrayList<>();
        while (!zeroInQueue.isEmpty()) {
            Node node = zeroInQueue.poll();
            result.add(node);
            for (Node next : node.nexts) {
                inMap.put(next, inMap.get(next) -1);
                if (inMap.get(next) == 0) {
                    zeroInQueue.add(next);
                }
            }
        }
        return result;
    }
}
